<?php
namespace control;
/*
*证照借用类
*/


class certificateBorrowClass extends adIndexClass
{
    private const title = '证照借用';
    private const page = 'certificateBorrow';
    private const table = 'certificate_borrow';
    private const tableMx = 'certificate_borrow_detail';
    private const stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'borrowedSearch':
                $tr = [
                    'workFlow'      => [
                        'name'  => "借用状态",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'cType'      => [
                        'name'  => "证照类型",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'name' => [
                        'name'  => "证照名称",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'cNo'  => [
                        'name'  => "证照编号",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'stName'         => [
                        'name'  => '申请借用人',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'company'          => [
                        'name'  => '借用人单位',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'type'          => [
                        'name'  => '借用方式',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'copyNum'          => [
                        'name'  => '复印份数',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'application'          => [
                        'name'  => '借用用途',
                        'width' => 160,
                    ],
                    'borrowDate'          => [
                        'name'  => '借出日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'exReturnDate'          => [
                        'name'  => '应还日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'returnDate'          => [
                        'name'  => '实际归还日期',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
                break;
            default:
                $tr = [
                    'workFlow'      => [
                        'name'  => "借用状态",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'cType'      => [
                        'name'  => "证照类型",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name' => [
                        'name'  => "证照名称",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'cNo'  => [
                        'name'  => "证照编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'stName'         => [
                        'name'  => '申请借用人',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'company'          => [
                        'name'  => '借用人单位',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type'          => [
                        'name'  => '借用方式',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'copyNum'          => [
                        'name'  => '复印份数',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'application'          => [
                        'name'  => '借用用途',
                        'width' => 150,
                    ],
                    'applyDate'          => [
                        'name'  => '申请日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '审批状态',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "证照类别" => select(["name" => "type", 'option' => explode('，', para('certType'))]),
                    "证照名称"     => text(array("name" => "name")),
                    "证照编号"     => text(array("name" => "cNo")),

                ],
                [
                    "申请借用人"     => text(array("name" => "stName")),
                    "借用人单位"     => text(array("name" => "company")),
                    '借阅方式'   => select(array("name" => "type", "option" => explode("，", para("borrowType")))),
                ],
                [
                    "审批状态" => select(array("name" => "state", "option" => self::stateOption)),
                    '申请日期'   => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*客户列表-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page . "&fun=detail";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "borrow")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','borrow',{})\" class='spanButton'>借出</span>\n";
        }
        if ($this->power(self::page, "copy")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','copy',{})\" class='spanButton'>复印</span>\n";
        }
        if ($this->power(self::page, "warrant")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}','authorization',{})\" class='spanButton'>临时授权</span>\n";
        }
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "a.company" => $this->post('company'),//借用人单位
            "a.stName" => $this->post('stName'),//标题
            "c.orderNo" => $this->post('cNo'),
            "c.name" => $this->post('name'),
        );
        //全等查询数组
        $equal = array(
            'b.workFlow' => '待借用',
            "c.type" => $this->post('type'),//公文种类
            "state" => $this->post('state'),
        );

        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: "a.time");
        }
        if (!$this->power(self::page, 'seeAll')) {
            $and .= " and (a.stid = '" . self::$stid . "' or a.staffId = '" . self::$stid . "')";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.applyDate desc,b.list',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table . " as a join " . self::tableMx . " as b on a.id = b.orderId join certificate as c on c.id = b.cid", 'field' => "b.*,a.company,c.type as cType,c.name,c.orderNo as cNo,a.stName,a.state,a.time as applyDate", "where" => $where, "order" => $orderBy['orderBy']));
        $json['sql'] = $page['sql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "draftId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page . "&fun=detail";
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "draftId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['orderId'] . "')"),
                "edit" => $array['state'] != '草稿' ? [] : array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['orderId'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 100),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $this->homeJs() . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function borrowedOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "证照类别" => select(["name" => "type", 'option' => explode('，', para('certType'))]),
                    "证照名称"     => text(array("name" => "name")),
                    "证照编号"     => text(array("name" => "cNo")),

                ],
                [
                    "申请借用人"     => text(array("name" => "stName")),
                    "借用人单位"     => text(array("name" => "company")),
                    '借阅方式'   => select(array("name" => "type", "option" => explode("，", para("borrowType")))),
                ],
                [
                    '借出日期'   => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ]);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /**
     * 已借用
     *
     */
    public function borrowed(): bool|string
    {
        $html = $this->borrowedOptions(false);
        $button = "";
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 已借用
     * @return bool|string
     */
    public function borrowedSearch(): bool|string
    {
        //like查询数组
        $like = array(
            "a.company" => $this->post('company'),//借用人单位
            "a.stName" => $this->post('stName'),//标题
            "c.orderNo" => $this->post('cNo'),
            "c.name" => $this->post('name'),
        );
        //全等查询数组
        $equal = array(
            'b.workFlow' => '已借用',
            "c.type" => $this->post('type'),//公文种类
            "state" => $this->post('state'),
        );

        $and = "";
        if ($this->post('time')) {
            $and .= self::timeComparison($this->post('time'), field: 'b.borrowDate');
        }
        if (!$this->power('certificateBorrowRecord', 'seeAll')) {
            $and .= " and (b.see like '%" . self::$stid . "%' or a.stid = '" . self::$stid . "' or a.staffId = '" . self::$stid . "')";
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.applyDate desc,b.list',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => self::table . " as a join " . self::tableMx . " as b on a.id = b.orderId join certificate as c on c.id = b.cid",
            'field' => "b.*,a.company,c.type as cType,c.name,c.orderNo as cNo,a.stName,a.state",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("abolishedForm", "abolishedId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "abolishedId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $array['orderId'] . "')"),
            );
            if (str_contains($array['see'], self::$stid)) {
                unset($dominate['detail']);
                if (strtotime($array['seeEndTime']) > time()) {
                    $array['cNo'] = "<span class='link' onclick=\"newIframe('证照详情','" . root . "control/adIndex.html?cla=certificate&fun=detail&id=" . $array['cid'] . "')\">" . $array['cNo'] . "</span>";
                }
            } else {
                $array['cNo'] = "<span class='link' onclick=\"newIframe('证照详情','" . root . "control/adIndex.html?cla=certificate&fun=detail&id=" . $array['cid'] . "')\">" . $array['cNo'] . "</span>";
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='abolishedForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 待借用JS
     * @return string
     */
    public function homeJs(): string
    {
        return <<<eof
<script>
function chooseStaff(){
   let stid =  $("[name='chooseStid']").val();
   let flag = true;
   $("[name='stid[]']").each(function() {
      let thisStid = $(this).val();
      if (stid===thisStid){
         flag = false;
      }
   })
   if (flag){
        $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=assembly',{stid:stid},function (res){
       if (res.warn ===2){
           $("#chooseButton").parent().before(res.html);
       }
     },'json')
   }
    $('#{$this->get('cla')}ChooseStaff').remove()
}
function delStaff(e){
    $(e).parent().remove();
}
</script>
eof;

    }

    /**
     * 组成范围人选
     *
     * @return bool|string
     */
    public function assembly(): bool|string
    {
        $stid = $this->post('stid');
        if (empty($stid)) {
            $json['warn'] = '请选择人员';
        } else {
            $staff = query('staff', "stid = '$stid'");
            $json['warn'] = 2;
            $json['html'] = <<<efo
                                    <li><input name="stid[]" type="hidden" value="{$staff['stid']}"><span class="staff-span li-ico" >{$staff['name']}</span><a href='javascript:void(0)' onclick="delStaff(this)"><div><span class='u-icon-delete'><i></i></span></div></a></li>
efo;
        }
        return json_encode($json, 320);
    }

    /**
     * 临时授权
     * @return bool|string
     */
    public function authorization(): bool|string
    {
        $formName = 'listForm';
        $btn = <<<eof
<div id="staffSelect">
<ul>
<li><span class="spanButton" style="margin-top: 0" id="chooseButton" onclick="layer('certificateBorrow','chooseStaff',{})">选择</span></li>
</ul>
</div>
<style>
#staffSelect ul li{float: left;}
.li-ico + a > div{left: -13px;top: -7px;}
.staff-span{padding: 2px 20px;background-color: rgba(242, 242, 242, 1)}
</style>
eof;
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "截止日期：" => text(array('name' => 'signTime', 'laydate' => ['type' => 'datetime'], 'value' => '')),
            ),
            array(
                must . "查看范围：" => selectMultiple(["name" => "stid[]", 'multiple' => true, 'title' => '请选择', 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name'])
            ),
        )));
        //返回
        return $this->layer(array("title" => "临时授权", "height" => 220, "width" => 700, "html" => $html, 'formTwo' => $formName));
    }

    /**
     * 临时授权
     */
    public function authorizationEdit(): bool|string
    {
        $idArr = $this->post('draftId');
        if (!$this->power(self::page, "warrant")) {
            $json['warn'] = "你没有" . self::title . "的临时授权权限";
        } elseif (static::is_null_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif (empty($this->post('signTime'))) {
            $json['warn'] = '请选择截止时间';
        } else {
            $x = 0;
            $text = '';
            $field = [
                'see' => $this->post('stid') ? implode(',', $this->post('stid')) : '',
                'seeEndTime' => $this->post('signTime'),
//                'workFlow' => '已借用',
                'returnState' => '',
            ];
            foreach ($idArr as $id) {
                $mx = query(self::tableMx, "id = '$id'");
                $info = query(self::table, "id = '$mx[orderId]'");
                $certificate = query('certificate', "id = '$mx[cid]'");
                if ($info['state'] != '已通过') {
                    $text .= $this->control['name'] . "授权查看证照【{$certificate['name']}】， id：{$id} 失败：还未审核通过<br>";
                } else {
                    $warn = update(array('table' => self::tableMx, 'field' => $field, 'where' => " id = '$id'"));
                    if ($warn == '更新成功') {
                        $x++;
                        //发送待办
                        $text .= $this->control['name'] . "授权查看证照【{$certificate['name']}】， id：{$id}成功，截止时间:{$this->post('signTime')}<br>";
                    } else {
                        $text .= $this->control['name'] . "授权查看证照【{$certificate['name']}】， id：{$id} 失败，更新失败<br>";
                    }
                }
            }
            if ($text) {
                //添加日志
                $this->logText(["type" => self::page, "text" => $text]);
            }
            $_SESSION['warn'] = "成功授权了{$x}个记录，详情请查看系统日志";
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 选择员工
     * @return bool|string
     */
    public function chooseStaff(): bool|string
    {
        $where = '';
        //生成表单
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    "查看人：" => selectMultiple(array('name' => 'chooseStid', 'title' => '请选择', 'table' => "staff", 'where' => " state in ('转正','试用')" . $where, 'sqlId' => 'stid', 'sqlField' => 'name')),
                ),
            ),
        ));
        //返回
        return $this->layer(array(
            "title" => "选择",
            'winFix' => true,
            "height" => 300,
            "width" => 800,
            "html" => $html,
            'button' => "<input onclick=\"chooseStaff()\" type='button' class='button' value='确认提交'>"
        ));
    }

    /**
     * 借出
     */
    public function borrow(): bool|string
    {
        $formName = 'listForm';
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "借出日期：" => text(array('name' => 'signTime', 'laydate' => [], 'value' => $this->date)),
            ),
            array(
                "应还日期：" => text(array('name' => 'backTime', 'laydate' => [], 'value' => '')),
            ),
        )));
        //返回
        return $this->layer(array("title" => "借出", "height" => 220, "html" => $html, 'formTwo' => $formName));
    }

    /**
     * 借出
     */
    public function borrowEdit(): bool|string
    {
        $idArr = $this->post('draftId');
        if (!$this->power(self::page, "borrow")) {
            $json['warn'] = "你没有" . self::title . "的借出权限";
        } elseif (static::is_null_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif (empty($this->post('signTime'))) {
            $json['warn'] = '请选择借出时间';
        } else {
            $x = 0;
            $text = '';
            foreach ($idArr as $id) {
                $mx = query(self::tableMx, "id = '$id'");
                $info = query(self::table, "id = '$mx[orderId]'");
                $certificate = query('certificate', "id = '$mx[cid]'");
                if ($info['state'] != '已通过') {
                    $text .= $this->control['name'] . "借出证照【{$certificate['name']}】， id：{$id} 失败：还未审核通过<br>";
                } elseif (static::total(array('table' => self::tableMx, "where" => "cid = '$mx[cid]' and type = '实物借出' and workFlow = '已借用' and returnState = '待归还'")) > 0) {
                    $text .= $this->control['name'] . "借出证照【{$certificate['name']}】， id：{$id} 失败：已借出<br>";
                } else {
                    $warn = update(array('table' => self::tableMx, 'field' => ['workFlow' => '已借用', 'returnState' => '待归还', 'borrowDate' => $this->post('signTime'), 'exReturnDate' => $this->post('backTime')], 'where' => " id = '$id'"));
                    if ($warn == '更新成功') {
                        $x++;
                        //发送待办
                        $text .= $this->control['name'] . "借出了证照【{$certificate['name']}】， id：{$id}成功，借出日期:{$this->post('signTime')}<br>";
                    } else {
                        $text .= $this->control['name'] . "借出了证照【{$certificate['name']}】， id：{$id} 失败，更新失败<br>";
                    }
                }
            }
            if ($text) {
                //添加日志
                $this->logText(["type" => self::page, "text" => $text]);
            }
            $_SESSION['warn'] = "成功借出了{$x}个证照，详情请查看系统日志";
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
            $json['warn'] = 2;
        }
        //返回
        return json_encode($json, 320);
    }


    /**
     * 复印
     */
    public function copy(): bool|string
    {
        $formName = 'listForm';
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "日期：" => text(array('name' => 'copyDate', 'laydate' => [], 'value' => $this->date)),
            ),
            array(
                must . '复印份数：' => text(array('name' => 'copyNum', 'class' => 'text'))
            )
        )));
        //返回
        return $this->layer(array("title" => "复印", "height" => 240, "width" => 600, "html" => $html, 'formTwo' => $formName));
    }

    /**
     * 复印
     */
    public function copyEdit(): bool|string
    {
        $idArr = $this->post('draftId');
        $field = array(
            'copyDate' => $this->post('copyDate'),
            'factCopyNum' => $this->post('copyNum'),
        );
        $annotation = [
            'copyDate' => '日期',
            'factCopyNum' => '复印份数',
        ];
        $rules = [
            'copyDate' => 'required',
            'factCopyNum' => 'required',
        ];
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if (!$this->power(self::page, "copy")) {
            $json['warn'] = "你没有" . self::title . "的复印权限";
        } elseif (static::is_null_array($idArr)) {
            $json['warn'] = "请选择数据";
        } elseif ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } else {
            $x = 0;
            $text = '';
            foreach ($idArr as $id) {
                $mx = query(self::tableMx, "id = '$id'");
                $info = query(self::table, "id = '$mx[orderId]'");
                $certificate = query('certificate', "id = '$mx[cid]'");
                if ($info['state'] != '已通过') {
                    $text .= $this->control['name'] . "填写借出证照【{$certificate['name']}】复印份数， id：{$id} 失败：还未审核通过<br>";
                } else {
                    $warn = update(array('table' => self::tableMx, 'field' => $field, 'where' => " id = '$id'"));
                    if ($warn == '更新成功') {
                        $x++;
                        //发送待办
                        $text .= $this->control['name'] . "填写了证照【{$certificate['name']}】的复印份数， id：{$id}，复印日期:{$field['copyDate']}<br>";
                    } else {
                        $text .= $this->control['name'] . "填写了证照【{$certificate['name']}】的复印份数， id：{$id} 失败，更新失败<br>";
                    }
                }
            }
            if ($text) {
                //添加日志
                $this->logText(["type" => self::page, "text" => $text]);
            }
            $_SESSION['warn'] = "成功填写了{$x}个证照借用记录，详情请查看系统日志";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        //返回
        return json_encode($json, 320);
    }


    /**
     *
     * @return bool|string
     */
    public function addMx(): bool|string
    {
        $html =
            select(["name" => "type", 'option' => explode('，', para('certType')), 'title' => '证照类别']) .
            text(array("name" => "name", "title" => "证照名称")) .
            text(array("name" => "orderNo", "title" => "证照编号")) .
            hidden(array('name' => 'cid', 'value' => $this->post('cid') ? implode(',', $this->post('cid')) : ''));
        $button = "<input style='margin-left: 5px' onclick=\"addRow()\" type='button' class='searchSub' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     *添加物料
     */
    public function addMxSearch(): bool|string
    {
        $cid = $this->post('cid') ? explode(',', $this->post('cid')) : [];
        $where = " 1=1 and id not in ('" . implode("','", $cid) . "')";
        $and = "";
        $like = [
            'orderNo' => $this->post('orderNo'),
            'name' => $this->post('name'),
        ];
        $equal = [
            'type' => $this->post('type'),
        ];
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "certificate",
            "where" => $where,
            'pageNum' => 50,
            "order" => "time ASC",
        ]);
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[] = [$checkAll, '证照类别', '证照名称', '证照编号'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "mxId", "value" => $array['id']),
            );
            $tr[] = array(
                $this->dominate($dominate),
                $array['type'],
                $array['name'],
                $array['orderNo'],
            );
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit(): bool|string
    {
        $mxIdArr = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择证照';
        } else {
            $tr = [];
            foreach ($mxIdArr as $mxId) {
                $certificate = query('certificate', "id = '$mxId'");
                $id = self::getId();
                $borrowType = select(array('name' => 'borrowType[]', 'title' => '借用方式', 'option' => explode('，', para('borrowType'))));
                $tr[] = [
                    componentClass::tablePperation('',"delTableRow(this)").
                    hidden(array('name' => 'mxId[]', 'value' => $id)) .
                    hidden(array('name' => 'cid[]', 'value' => $mxId)),
                    $certificate['type'],
                    $certificate['name'],
                    $certificate['orderNo'],
                    $borrowType,
                    text(array('name' => 'copyNum[]', 'value' => '')),
                    text(array('name' => 'application[]', 'value' => '')),
                    text(array('name' => 'mxText[]', 'value' => '')),
                ];
            }
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }


    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id')?:suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => "保存",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];

        $tr[] = ['', '证照类别', '证照名称', '证照编号', must . '借用方式', '复印份数', '借用用途', '备注'];
        $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
        foreach ($result['array'] as $k=>$array) {
            $certificate = query('certificate', " id = '$array[cid]'");
            $tr[] = [
                componentClass::tablePperation($k+1,"delTableRow(this)").
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                hidden(array('name' => 'cid[]', 'value' => $array['cid'])),
                $certificate['type'],
                $certificate['name'],
                $certificate['orderNo'],
                select(array('name' => 'borrowType[]', 'title' => '借用方式', 'option' => explode('，', para('borrowType')), 'value' => $array['type'])),
                text(array('name' => 'copyNum[]', 'value' => $array['copyNum'])),
                text(array('name' => 'application[]', 'value' => $array['application'])),
                text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => $array['text'])),
            ];
        }
        $table = $this->listTable(array('tr' => $tr, 'end' => true));
        $smallButton = <<<efo
<span class="smallButton" onclick="layer('{$this->get('cla')}','addMx',$('form[name={$this->get('cla')}EditForm]').serialize())">选择证照</span>
efo;


        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "借用人：" =>  selectMultiple(["name" => "staffId", 'change' => 'getStaffName', 'class' => 'width100', 'title' => '请选择', 'table' => 'staff', 'where' => "state !='离职'", 'sqlId' => 'stid', 'sqlField' => 'name', "value" => $info['staffId']]) . text(["name" => "stName", 'class' => 'width100', "value" => $info['stName']]),
                    must . "申请借用日期：" => text(["name" => "applyDate", 'laydate' => [], "value" => $info['applyDate']]),

                    "借用单位：" => text(["name" => "company", 'class' => 'text', "value" => $info['company']]),
                    "借用人证件类型：" => select(["name" => "certificateType", 'value' => $info['certificateType'], 'option' => explode('，', para('certificateType')), 'title' => '证件类型']),
                ],
                [
                    "证件号码：" => text(["name" => "certificateNo", "value" => $info['certificateNo']]),
                ],
                [
                    "备注：" => textarea(["name" => "text", "value" => $info['text']])
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '明细',
            'button' => $smallButton,
            'html' => $table,
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        //返回
        return $this->tab($data) . $this->editJs();
    }

    public function editJs(): string
    {
        return <<<eof
<script>
function getStaffName(e){
    let stid = e.value;
    if (stid){
        $.post(root+'control/adIndex.html?cla=certificateBorrow&fun=getStffName',{stid:stid},function(res) {
           $("[name='stName']").val(res.name);
        },'json')
    }
}
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
        $('#certificateBorrowAddMx').hide();
        $("#materialTable tbody").append(res.html);
        resetNumber($("#materialTable"))
    },'json');
}
</script>
eof;

    }

    /**
     * 获取员工姓名
     * @return bool|string
     */
    public function getStffName(): bool|string
    {
        $stid = $this->post('stid');
        $staff = query('staff', "stid = '$stid'");
        $json['name'] = $staff['name'];
        return json_encode($json, 320);
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId');
        $cidArr = $this->post('cid');
        $typeArr = $this->post('borrowType');
        $copyNumArr = $this->post('copyNum');
        $applicationArr = $this->post('application');
        $mxTextArr = $this->post('mxText');

        $field = [
            'staffId' => $this->post('staffId'),
            'stName' => $this->post('stName'),
            'applyDate' => $this->post('applyDate'),
            'text' => $this->post('text'),
            'company' => $this->post('company'),
            'certificateType' => $this->post('certificateType'),
            'certificateNo' => $this->post('certificateNo'),
        ];
        if ($field['staffId']) {
            $field['stName'] = self::findStaff($field['staffId']);
        }
        $annotation = [
            'stName' => '借用人',
            'applyDate' => '申请借用日期',
        ];
        $rules = [
            'stName' => 'required',
            'applyDate' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = '请选择需要借用的证照';
        } elseif (static::is_null_array($cidArr)) {
            $json['warn'] = '请选择需要借用的证照';
        } elseif (static::is_null_array($typeArr)) {
            $json['warn'] = '请选择借用方式';
        } else {
            $this->startTrans();
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'ZZJY' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'state' => '草稿',
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            foreach ($mxIdArr as $k => $mxId) {
                $mx = query(self::tableMx, "id = '$mxId'");
                if (empty($mx['id'])) {
                    $warn = static::insert(array(
                        'table' => self::tableMx,
                        'field' => [
                            'id' => $mxId,
                            'orderId' => $id,
                            'cid' => $cidArr[$k],
                            'type' => $typeArr[$k],
                            'copyNum' => $copyNumArr[$k],
                            'application' => $applicationArr[$k],
                            'text' => $mxTextArr[$k],
                        ]
                    ));
                } else {
                    $warn = static::update(array(
                        'table' => self::tableMx,
                        'field' => [
                            'type' => $typeArr[$k],
                            'copyNum' => $copyNumArr[$k],
                            'application' => $applicationArr[$k],
                            'text' => $mxTextArr[$k],
                        ],
                        'where' => "id = '$mx[id]'"
                    ));
                }
                if (!in_array($warn, ["新增成功", "更新成功"])) {
                    $json['warn'] = $warn;
                    break;
                }
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 审核按钮
     *
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
          if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => [
                    "act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'name' => '证照借用',
                        'table' => self::table,
                        'process' => [
                            // 预览函数
                            'detail' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'detail',
                            ],
                            //执行发起时验证函数
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'beforeValidate',
                                'data' => ['id' => $info['id']]
                            ],
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        // 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => [
                    "act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state'],   //变更字段 可多个
                        'value' => [
                            'state' => ['草稿', '已通过'],
                        ],
                        // 审核时回调
                        'process' => [
                            //执行首次审核时验证
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //执行末次审核后处理
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
                'style' => 'li-btn-blue-bg',
            ];
        }
        $num = static::total(array('table' => self::tableMx, "where" => "orderId = '$info[id]' and workFlow !='待借用'"));
        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿' && $num == 0) {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state'],   //变更字段 可多个
                        'value' => [
                            'state' => ['草稿'],
                        ],
                        'process' => [
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        return $button;
    }

    /**
     * 提交审批前验证
     */
    public function beforeValidate($data)
    {
        $info = query(self::table, "id = '$data[id]'");
        $all = find(array('table' => self::tableMx, "where" => "orderId = '$info[id]' order by list asc"));
        foreach ($all['array'] as $array) {
            if (static::total(array('table' => self::tableMx, "where" => "cid = '$array[cid]' and type = '实物借出' and workFlow = '已借用' and returnState = '待归还'")) > 0) {
                $certificate = query('certificate', "id = '$array[cid]'");
                return "证照【{$certificate['name']}】-【{$certificate['orderNo']}】已借出";
            }
        }
        return true;
    }

    /*客户管理-客户详情页*/
    public function detail()
    {
        $info = query(self::table, "id = '" . $this->get('id') . "'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $tr[] = ['证照类别', '证照名称', '证照编号', '借用方式', '复印份数','实际复印份数','复印日期', '借用用途', '备注', '借出日期', '应还日期', '实际归还日期'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            $total_tr = [4 => 0, 5 => 0];
            foreach ($result['array'] as $array) {
                $certificate = query('certificate', " id = '$array[cid]'");
                if (str_contains($array['see'], self::$stid)) {
                    if (strtotime($array['seeEndTime']) > time()) {
                        $certificate['orderNo'] = "<span class='link' onclick=\"newIframe('证照详情','" . root . "control/adIndex.html?cla=certificate&fun=detail&id=" . $array['cid'] . "')\">" . $certificate['orderNo'] . "</span>";
                    }
                } else {
                    $certificate['orderNo'] = "<span class='link' onclick=\"newIframe('证照详情','" . root . "control/adIndex.html?cla=certificate&fun=detail&id=" . $array['cid'] . "')\">" . $certificate['orderNo'] . "</span>";
                }
                $tr[] = [
                    $certificate['type'],
                    $certificate['name'],
                    $certificate['orderNo'],
                    $array['type'],
                    $array['copyNum'],
                    $array['factCopyNum'],
                    $array['copyDate'],
                    $array['application'],
                    $array['text'],
                    $array['borrowDate'],
                    $array['exReturnDate'],
                    $array['returnDate'],
                ];
                $total_tr[4] += $array['copyNum'];
                $total_tr[5] += $array['factCopyNum'];
            }
            //按钮
            $button = [];

            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "顶部页卡",
                    "title" => "编辑",
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],
                ];

            }
            if ($this->power(self::page, "del") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            //审核按钮
            $button = array_merge($this->auditButton($info),$button);
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        "借用人" => $info['stName'],
                        "申请借用日期" => $info['applyDate'],
                        "借用单位" => $info['company'],
                        "证件类型" => $info['certificateType'],
                    ),
                    array(
                        "证件号码" => $info['certificateNo'],
                        "单据编号" => $info['orderNo'],
                        "制单人" => self::findStaff($info['stid']),
                        "审核状态" => $info['state'],
                    ),
                    array(
                        "备注" => pre($info['text']),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '明细',
                'html' => $this->listTable(array('tr' => $tr, 'showSort' => true, 'total' => $total_tr)),
            ]);
            $data['html'] .= $this->detailBlock([
                '流程' => auditClass::auditRecord(self::table, $info['id'])
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete(): bool|string
    {
        $array = $this->post('draftId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id'");
                if ($info['state'] != '草稿') {
                    //返回
                    $warn = "删除失败：不是草稿状态";
                } else {
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            if ($text) {
                $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
                $this->logText(array("type" => self::page, "text" => $text));
            }
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
}
